package com.itheima.kafka.demo.producer;

import org.apache.kafka.clients.producer.*;

import java.util.Date;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * 生产者
 */
public class ProducerQuickStart100 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //1.kafka的配置信息
        Properties properties = new Properties();
        //kafka的连接地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.200.130:9092");
        //发送失败，失败的重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG,5);
        //消息key的序列化器
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        //消息value的序列化器
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.ACKS_CONFIG,"all");

        //2.生产者对象
        KafkaProducer<String,String> producer = new KafkaProducer<String, String>(properties);


        //封装发送的消息
//        ProducerRecord<String,String> record = new ProducerRecord<String, String>("itheima-topic-testpartition",null,"hello kafka"+new Date());

        //该消息只发送到  itheima-topic-testpartition  的1号分区中
        ProducerRecord<String,String> record = new ProducerRecord<String, String>("itheima-topic-testpartition",0,null,"hello kafka"+new Date());

        //3.发送消息  -同步
        Future<RecordMetadata> send = producer.send(record);
        System.out.println("--------同步日志");
        System.out.println(send.get().topic());//主题
        System.out.println(send.get().partition());//分区
        System.out.println(send.get().offset());//消息在kafka中的偏移量   下标   同一个主题下消息下标是递增的
        //3.发送消息  -异步
        producer.send(record, new Callback() {
            @Override
            public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                if(e != null){
                    System.out.println("记录异常信息到日志表中");
                }
                System.out.println("--------异步日志");
                System.out.println(recordMetadata.topic());
                System.out.println(recordMetadata.partition());
                System.out.println(recordMetadata.offset());
            }
        });


        /*for(int i=0;i<30;i++){
            ProducerRecord<String,String> record = new ProducerRecord<String, String>("itheima-topic-testpartition",null,"hello kafka"+new Date());

            //3.发送消息
            Future<RecordMetadata> send = producer.send(record);
            System.out.println(send.get().topic());//主题
            System.out.println(send.get().partition());//分区
            System.out.println(send.get().offset());//消息在kafka中的偏移量   下标   同一个主题下消息下标是递增的
        }*/



        //4.关闭消息通道，必须关闭，否则消息发送不成功
        producer.close();
    }

}